<template>
    <div class="inventory-check-form">
        <div class="section">
            <h2 class="section-title">修改盘点单</h2>
            <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="qty_order" status-icon
                :rules="rules" label-width="auto" class="demo-ruleForm">
                <el-form-item label="盘点单号" prop="qty_code">
                    <el-input v-model="qty_order.qty_code" readonly />
                </el-form-item>
                <div style="display: flex; justify-content: space-between;">
                    <div style="width: 48%;">
                        <el-form-item label="盘点类型" prop="qty_type" style="margin-bottom: 30px;">
                            <el-select v-model="qty_order.qty_type" placeholder="请选择盘点类型">
                                <el-option v-for="item in options" :key="item.dict_value" :label="item.dict_label"
                                    :value="item.dict_value" class="option-style" />
                            </el-select>
                        </el-form-item>



                        <el-form-item label="盘点库区" prop="" style="margin-bottom: 30px;">
                            <el-select v-model="qty_order.zone_code" placeholder="请选择盘点库区" @change="handleSzone"
                                :disabled="dialogTableVisibleCk">
                                <el-option v-for="item in Warhouse_zone" :key="item.zone_code" :label="item.zone_name"
                                    :value="item.zone_code" />
                            </el-select>
                        </el-form-item>


                        <el-form-item label="开始日期" prop="qty_startdate" style="margin-bottom: 30px;">
                            <el-date-picker v-model="qty_order.qty_startdate" type="datetime" placeholder="选择日期时间"
                                style="width: 100%;" />
                        </el-form-item>
                    </div>

                    <div style="width: 48%;">

                        <el-form-item label="盘点仓库" prop="warehouse_code" style="margin-bottom: 30px;">
                            <el-select v-model="qty_order.warehouse_code" placeholder="请选择盘点仓库"
                                @change="handleSelectChange" :disabled="dialogTableVisibleCk">
                                <el-option v-for="item in warehouses" :key="item.warehouse_code"
                                    :label="item.warehouse_name" :value="item.warehouse_code" />
                            </el-select>
                        </el-form-item>


                        <el-form-item label="结束日期" prop="qty_end" style="margin-bottom: 30px;">
                            <el-date-picker v-model="qty_order.qty_end" type="datetime" placeholder="选择日期时间"
                                style="width: 100%;" />
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </div>

        <div class="section">
            <h2 class="section-title">盘点产品明细</h2>
            <div style="float: left;margin: 10px 0px;">
                <el-button type="primary" @click="productAdd">添加</el-button>
                <el-button type="primary" @click="productDel">移除</el-button>

            </div>
            <el-table :data="selectedData" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                textAlign: 'center',
                background: '#f5f7fa',
                fontWeight: 'bold',
                position: 'sticky',
                top: 0
            }" ref="selectedTable" @selection-change="handleSelectedChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="pro_name" label="货品名称" fixed="left" width="150" />
                <el-table-column prop="pro_code" label="货品编号" width="150" />
                <el-table-column prop="pro_brand" label="品牌" width="100" />
                <el-table-column prop="pro_model" label="规格型号" width="100" />
                <el-table-column label="单位" width="70">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.dict_code) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="location_code" label="盘点库位" width="130">
                    <template #default="scope">
                        <el-select v-model="scope.row.location_name" placeholder="选择库位" size="small"
                            @change="(val) => locationEndit(val, scope.row)">
                            <el-option v-for="item in Warehouse_location" :key="item.location_code"
                                :label="item.location_name" :value="item.location_code" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="stock_numder" label="库存数量" width="100" />
                <el-table-column label="盘点数量" width="110">
                    <template #default="scope">
                        <el-input v-model="scope.row.inventory_numder" style="width: 75px" :precision="0" :min="0"
                            @change="calculateProfitLoss(scope.row)" />

                    </template>
                </el-table-column>

                <el-table-column prop="proddti_profit" label="盘盈数量" width="100">
                    <template #default="scope">
                        <span :style="{color: scope.row.proddti_profit > 0 ? '#67C23A' : '#606266'}">
                            {{ scope.row.proddti_profit }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="proddti_loss" label="盘亏数量" width="100">
                    <template #default="scope">
                        <span :style="{color: scope.row.proddti_loss > 0 ? '#F56C6C' : '#606266'}">
                            {{ scope.row.proddti_loss }}
                        </span>
                    </template>
                </el-table-column>

                <el-table-column prop="pro_cost_price" label="成本价" width="90" />

                <el-table-column label="盘盈金额" width="110">
                    <template #default="scope">
                        <span :style="{color: scope.row.proddti_profit_money > 0 ? '#67C23A' : '#606266'}">
                            {{ scope.row.proddti_profit_money.toFixed(2) }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="盘亏金额" width="110">
                    <template #default="scope">
                        <span :style="{color: scope.row.proddti_loss_money > 0 ? '#F56C6C' : '#606266'}">
                            {{ scope.row.proddti_loss_money.toFixed(2) }}
                        </span>
                    </template>
                </el-table-column>
            </el-table>
            <div style="height: 40px; line-height: 40px; padding: 0 20px;">
                <div style="display: flex; justify-content: space-between;">
                    <div>合计</div>
                    <div>
                        盘盈总数：<span style="color: #67C23A; font-weight: bold">{{ profit_total_qty }}</span>
                        &nbsp;&nbsp;&nbsp;盘亏总数：<span style="color: #F56C6C; font-weight: bold">{{ loss_total_qty
                            }}</span>
                        &nbsp;&nbsp;&nbsp;盘盈总金额：<span style="color: #67C23A; font-weight: bold">{{
                            profit_total_price.toFixed(2) }}</span>
                        &nbsp;&nbsp;&nbsp;盘亏总金额：<span style="color: #F56C6C; font-weight: bold">{{
                            loss_total_price.toFixed(2) }}</span>
                    </div>
                </div>
            </div>
        </div>



        <div class="button-group">
            <el-button type="primary" @click="handleUpdate">保存修改</el-button>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>

    <!-- 添加产品模态框 -->
    <el-dialog v-model="dialogTableVisible" width="800" title="添加产品">
        <hr>
        <div style="margin: 10px 0px;">
            <div style="float: left;margin: 10px 0px;">
                <el-input v-model="productcode" style="width: 240px;margin-right: 20px;" placeholder="请输入货品编号/名称" />
                <el-select v-model="dict_code" placeholder="请选择单位" style="width: 240px">
                    <el-option v-for="item in measureOptios" :key="item.dict_value" :label="item.dict_label"
                        :value="item.dict_value" />
                </el-select>
            </div>
            <div style="float: right;margin: 10px 0px;">
                <el-button @click="productReset">重置</el-button>
                <el-button type="primary" @click="productSearch">查询</el-button>
            </div>
        </div>
        <el-table ref="multipleTableRef" :data="productData" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
                textAlign: 'center',
                background: '#f5f7fa',
                fontWeight: 'bold',
                position: 'sticky',
                top: 0
            }" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" :selectable="isDisabled" />
            <el-table-column property="pro_code" label="货品编号" width="180" />
            <el-table-column property="stock_name" label="货品名称" width="200" />
            <el-table-column property="stock_model" label="规格型号" />
            <el-table-column label="单位">
                <template #default="scope">
                    <span>{{ measureValue(scope.row.dict_code) }}</span>
                </template>
            </el-table-column>
            <el-table-column property="pro_cost_price" label="成本价" />
            <el-table-column property="pro_sale_price" label="销售价" />
            <el-table-column property="stock_numder" label="当前库存" />
        </el-table>
        <br>
        <div style="text-align: center;display: flex; justify-content: center;">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
                :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" size="small" />
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogTableVisible = false">取消</el-button>
                <el-button type="primary" @click="handleConfirmSelection">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'

import { ElMessage } from 'element-plus';
import { useWarehouseStore } from '@/storejs/warehouseStore';
import { useRouter } from 'vue-router';



//库区列表
const Warhouse_zone = ref([]);

// 页面跳转获取数据
const router = useRouter();

const warehouseStore = useWarehouseStore()
const qty_code = ref(warehouseStore.qty_code || '')


// 仓库列表
const warehouses = ref([]);

// 盘点类型
const options = ref([])

const isSaved = ref(false); // 是否修正


//库位列表
const Warehouse_location = ref([]);

// 盘点单对象
let qtyAdd = {
    qty_id: 0,
    qty_type: "",
    qty_code: "",
    qty_clerk: localStorage.getItem('userLName'),
    qty_startdate: "",
    qty_end: "",
    warehouse_code: "",
    warehouse_name: "",
    zone_code: "",
    zone_name: "",
    update_by: localStorage.getItem('userLName'),
    update_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
    proddti_correct:"1",
}

// 盘点单表单对象
const qty_order = reactive({ ...qtyAdd })

const ruleFormRef = ref(null)
const rules = reactive({});


// 产品相关状态
const dialogTableVisible = ref(false) // 控制添加产品模态框的显示/隐藏
const productData = ref([])          // 存储从API获取的可添加产品列表
const currentPage = ref(1)           // 产品列表的当前页码（用于分页）
const pageSize = ref(5)              // 每页显示的产品数量（用于分页）
const pageCount = ref(0)             // 产品总数（用于分页）

const productcode = ref("")          // 产品搜索关键字（按名称或编号）
const dict_code = ref("0")           // 按计量单位筛选产品的条件
const measureOptios = ref([])        // 计量单位选项列表（从字典API获取）

const multipleTableRef = ref(null);  // 产品选择表格的DOM引用（用于操作表格）
const selectedProducts = ref([]);    // 在产品模态框中临时选中的产品（尚未确认添加）

const selectedTable = ref(null);     // 已选产品表格的DOM引用（用于操作表格）
const selectedRows = ref([]);        // 在已选产品表格中选中的行（用于删除操作）
const selectedData = ref([]);        // 最终确认添加到盘点单中的产品列表

// 盘点单统计信息
const profit_total_qty = ref(0)      // 盘盈总数
const loss_total_qty = ref(0)        // 盘亏总数
const profit_total_price = ref(0)    // 盘盈总金额
const loss_total_price = ref(0)      // 盘亏总金额

const dialogTableVisibleCk = ref(true) // 控制添加产品模态框的显示/隐藏

// 计算盈亏
// const calculateProfitLoss = (row) => {
  
   
    
//     const actual = Number(row.stock_numder);//库存数量
//     const inventory = Number(row.inventory_numder);//盘点数量
    
//     var proddti_loss=Number(row.proddti_loss);
//     proddti_loss.value=0;
   


//     if (inventory > actual) {
    
//         // 盘盈
//         row.proddti_profit = inventory - actual;//盘盈数量

//         row.proddti_loss = 0;//盘亏数量
//         row.proddti_profit_money = row.proddti_profit * row.pro_cost_price;
//         row.proddti_loss_money = 0;//盘亏金额
//     } else if (inventory <= actual) {
       
//         row.proddti_profit = 0;//盘盈数量
//         if (proddti_loss.value>0){
//             row.proddti_loss = proddti_loss;//盘亏数量
//             row.proddti_profit_money = 0;//盘盈金额
//             row.proddti_loss_money = row.proddti_loss * row.pro_cost_price;
//         }else{
//             row.proddti_loss = actual - inventory;//盘亏数量
//             row.proddti_profit_money = 0;//盘盈金额
//             row.proddti_loss_money = row.proddti_loss * row.pro_cost_price;
//         }
      
//     } else {
//         // 无盈亏
//         row.proddti_profit = 0;
//         row.proddti_loss = 0;
//         row.proddti_profit_money = 0;
//         row.proddti_loss_money = 0;
//     }
    
//     updateTotals();
// };
const calculateProfitLoss = (row) => {
    const actual = Number(row.stock_numder); // 库存数量
    const inventory = Number(row.inventory_numder); // 盘点数量

    // 重置盘盈和盘亏数量
    row.proddti_profit = 0;
    row.proddti_loss = 0;

    if (inventory > actual) {
        // 盘盈
        row.proddti_profit = inventory - actual; // 盘盈数量
        row.proddti_loss = 0; // 盘亏数量
        row.proddti_profit_money = row.proddti_profit * row.pro_cost_price; // 盘盈金额
        row.proddti_loss_money = 0; // 盘亏金额
    } else if (inventory < actual) {
        // 盘亏
        row.proddti_loss = actual - inventory; // 盘亏数量
        row.proddti_profit = 0; // 盘盈数量
        row.proddti_profit_money = 0; // 盘盈金额
        row.proddti_loss_money = row.proddti_loss * row.pro_cost_price; // 盘亏金额
    } else {
        // 无盈亏
        row.proddti_profit = 0;
        row.proddti_loss = 0;
        row.proddti_profit_money = 0;
        row.proddti_loss_money = 0;
    }

    updateTotals();
};
// 更新合计数据
const updateTotals = () => {
    profit_total_qty.value = 0;
    loss_total_qty.value = 0;
    profit_total_price.value = 0;
    loss_total_price.value = 0;

    selectedData.value.forEach(row => {
        profit_total_qty.value += Number(row.proddti_profit);
        loss_total_qty.value += Number(row.proddti_loss);
        profit_total_price.value += Number(row.proddti_profit_money);
        loss_total_price.value += Number(row.proddti_loss_money);
    });
};

// 点击修改按钮
async function handleUpdate() {
    try {
        // 更新修改人和修改时间
        qty_order.update_by = localStorage.getItem('userLName');
        qty_order.update_time = dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ');

        // 转换明细数据
        const detailList = selectedData.value.map(item => ({
            proddti_id: item.proddti_id || 0,
            qty_id: qty_order.qty_id,
            pro_name: item.pro_name,
            pro_code: item.pro_code,
            pro_brand: item.pro_brand,
            unitmeas_id: String(item.unitmeas_id || ""),
            pro_model: item.pro_model,
            inventory_numder: Number(item.inventory_numder) || 0,
       
            proddti_profit: Number(item.proddti_profit) || 0,
            proddti_loss: Number(item.proddti_loss) || 0,
            proddti_profit_money: Number(item.proddti_profit_money) || 0,
            proddti_loss_money: Number(item.proddti_loss_money) || 0,
            pro_cost_price: Number(item.pro_cost_price),
            location_code: item.location_code || "",    
            location_name: item.location_name || ""
        }));
      
        // 发送更新请求
        const response = await axios.put(
            "http://localhost:5181/api/Inv_Qty/Inv_Qty_Update",
            {
                inv_QtyUpdateDetailsDto: {
                    qty_id: qty_order.qty_id,
                    qty_type: qty_order.qty_type,
                    qty_code: qty_order.qty_code,
                    qty_clerk: qty_order.qty_clerk,
                    qty_startdate: qty_order.qty_startdate,
                    qty_end: qty_order.qty_end,
                    warehouse_code: qty_order.warehouse_code,
                    warehouse_name: qty_order.warehouse_name,
                    update_by: qty_order.update_by,
                    update_time: qty_order.update_time,
                    qty_audit_status: qty_order.qty_audit_status,
                    Zone_code: qty_order.zone_code,
                    Zone_name: qty_order.zone_name
                },
                inv_proddtiList: detailList
            },
            {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }
        );

        if (response.data > 0) {
            ElMessage.success("盘点单修改成功");
            selectedData.value = [];
            handleClose();
            router.push('/main/Inv/InvQty');
        } else {
            ElMessage.error("修改失败");
        }
    } catch (error) {
        console.error("修改出错:", error);
        ElMessage.error("修改过程中发生错误: " + (error.response?.data || error.message));
    }
}

// 加载修改的数据
async function loadEditData() {
  
    axios.get("http://localhost:5181/api/Inv_Qty/Inv_Qty_SelectCode", {
        params: {
            qty_code: qty_code.value
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((res) => {
        const mainData = res.data[0];

        // 填充主表数据
        Object.assign(qty_order, {
            qty_id: mainData.qty_id,
            qty_code: mainData.qty_code,
            qty_type: mainData.qty_type,
            qty_clerk: mainData.qty_clerk,
            qty_startdate: mainData.qty_startdate,
            qty_end: mainData.qty_end,
            qty_audit_status: mainData.qty_audit_status,
            qty_audit_by: mainData.qty_audit_by,
            qty_audit_time: mainData.qty_audit_time,
            qty_audit_opinion: mainData.qty_audit_opinion,
            warehouse_code: mainData.warehouse_code,
            warehouse_name: mainData.warehouse_name,
            zone_code: mainData.zone_code,
            zone_name: mainData.zone_name,
            proddti_correct: mainData.proddti_correct,
        });
        

       

        // 加载产品明细
        loadProductDetails();

        // 加载仓库列表
        getWarehouses();

         zone_codeSelect(); // ✅ 自动加载库区

        //自动加载库位
        getWarehouse_location();


          productCount();
        if (qty_order.proddti_correct === '1') {
          //修正
            isSaved.value=true;
        }else{
            //没有修正
            isSaved.value = false;
        }
            
    }).catch((res) => {
        console.log(res)
        ElMessage.error("加载盘点单数据失败");
    })
}

// 加载产品明细数据
function loadProductDetails() {
    axios.get("http://localhost:5181/api/Inv_Qty/Inv_Qty_SelectDetail", {
        params: {
            qty_code: qty_order.qty_code
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then(async(result) => {
        const tempData = [];

        for (const item of result.data) {
            // 获取当前产品的库存
            const stockNumber = await StockSelect(
                qty_order.warehouse_code,
                item.pro_code
            );

            tempData.push({
                ...item,
                proddti_id: item.proddti_id,
                inventory_numder: item.inventory_numder,
                pro_name: item.pro_name,
                stock_numder: stockNumber,
                pro_model: item.pro_model,
                unitmeas_id: item.unitmeas_id,
                pro_cost_price: item.pro_cost_price,
                proddti_loss: item.proddti_loss,
                isEditable: false, // ❗加载的数据不可编辑
                location_code: item.location_code,
                location_name: item.location_name,
                dict_code: item.unitmeas_id,
            });
        }



        selectedData.value = tempData;
        

        
        // 计算初始盈亏
        selectedData.value.forEach(row => {
           
       

            calculateProfitLoss(row);
        });
        
        updateTotals();
    }).catch((error) => {
        console.error("加载产品明细失败:", error);
        ElMessage.error('加载产品明细失败');
    });
}

  
//入库库位
function getWarehouse_location() {

    axios.get("http://localhost:5181/api/Db_warehouse_location/warehouse_location", {
        params: {
            zone_code: qty_order.zone_code,
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        Warehouse_location.value = result.data;
    }).catch((err) => {
        console.info(err)
    })
}

// 修正库存
const handleCorrectStock = async () => {
    // 1. 只允许新添加且盘亏 > 0 的产品
    const itemsToCorrect = selectedData.value.filter(
        item => item.isEditable && Number(item.proddti_loss) > 0
    );

    // 1. 当前被选中的行
    const currentSelected = selectedRows.value;
    if (currentSelected.length === 0) {
        ElMessage.warning('请先选择要修正的数据');
        return;
    }

    // // 2. 如果有盘盈数据 → 提示并终止
    // const profitItems = selectedData.value.filter(
    //     item => item.isEditable && Number(item.proddti_profit) > 0
    // );
    // if (profitItems.length > 0) {
    //     ElMessage.warning('盘盈数据不可进行库存修正');
    //     return;
    // }

    if (itemsToCorrect.length === 0) {
        ElMessage.warning('没有可修正的盘亏数据');
        return;
    }

    // 2. 检测选中行里是否有盘盈
    const hasSelectedProfit = currentSelected.some(
        row => Number(row.proddti_profit) > 0
    );
    if (hasSelectedProfit) {
        ElMessage.warning('选中的盘盈产品不可进行库存修正');
        return;
    }

    // 2. 构建参数
    const params = itemsToCorrect.map(item => ({
        warehouse_code: qty_order.warehouse_code,
        zone_code: qty_order.zone_code,
        location_code: item.location_code,
        pro_code: item.pro_code,
        stock_numder: Number(item.inventory_numder) // 修正后的库存
    }));

        //console.log(params);
    try {
        const res = await axios.put(
            'http://localhost:5181/api/Inv_Stock/Update_inv_Stock_numder',
            params,
            {
                headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
            }
        );

        if (res.data > 0) {
            ElMessage.success('库存修正成功');
            // 3. 重新加载明细（保持当前仓库）
            //loadProductDetails();
            // 获取当前产品的库存
            for (const item of params) {
                const stockNumber = await StockSelect(
                    qty_order.warehouse_code,
                    item.pro_code
                );

                // 找到对应的产品并更新库存数量
                const foundItem = selectedData.value.find(dataItem => dataItem.pro_code === item.pro_code);
                if (foundItem) {
                    foundItem.stock_numder = stockNumber; // 更新库存数量
                }
            }
         


        } else {
            ElMessage.error('库存修正失败');
        }
    } catch (err) {
        console.error(err);
        ElMessage.error('请求失败');
    }
};


// 根据仓库编码和产品编码查询库存信息
function StockSelect(warehouse_code, pro_code) {
    return axios.get("http://localhost:5181/api/Inv_Stock/GetinvStock", {
        params: {
            weahouse_code: warehouse_code,
            por_code: pro_code,
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((res) => {
        return res.data;
    }).catch((res) => {
        console.log(res);
    })
}


//事件触发--仓库变化
const handleSelectChange = async (selectedValue) => {
    const selectedItem = warehouses.value.find(item => item.warehouse_code === selectedValue);
    qty_order.warehouse_name = selectedItem.warehouse_name;


    //盘点仓库是否冻结
    if (selectedItem.warehouse_freeze === '0') {
        ElMessage.warning('该仓库未冻结');
        qty_order.warehouse_code = "";
        qty_order.warehouse_name = "";
    }


    // 清空库区和库位
    qty_order.zone_code = '';
    qty_order.zone_name = '';

    
    Warehouse_location.value = [];

    // 清空已选产品明细中的库位信息
    selectedData.value.forEach(item => {
        item.location_code = '';
        item.location_name = '';
    });


    // 重新加载库区
    await zone_codeSelect();

    updateTotals();
};


const zone_codeSelect = async () => {
    if (!qty_order.warehouse_code) {
        Warhouse_zone.value = [];
        return;
    }

    try {
        const res = await axios.get("http://localhost:5181/api/Db_warehouse_zone/warehouse_zone", {
            params: { warehouse_code: qty_order.warehouse_code },
            headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        Warhouse_zone.value = res.data || [];
    } catch (err) {
        console.error("加载库区失败:", err);
        ElMessage.error("加载库区失败");
    }
};

// 选择入库库区的时触发--事件触发--库区
const handleSzone = (value) => {
    const selectedItemzone = Warhouse_zone.value.find(item => item.zone_code == value)
    qty_order.zone_name = selectedItemzone.zone_name;

    //获取库位
    getWarehouse_location();
}

//选择入库库位的触发事件
const locationEndit = (value, row) => {
    // 1. 直接更新当前行的数据
    row.location_code = value; // 确保location_code更新
    const selectedItem = Warehouse_location.value.find(item => item.location_code === value);
    row.location_name = selectedItem ? selectedItem.location_name : '';


};
function productAdd() {
    dialogTableVisible.value = true
    productFill();
}

// 移除选中的table控件数据
const productDel = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要移除的数据');
        return;
    }

    const selectedCodes = selectedRows.value.map(item => item.pro_code);
    selectedData.value = selectedData.value.filter(
        item => !selectedCodes.includes(item.pro_code)
    );

    if (selectedTable.value) {
        selectedTable.value.clearSelection();
    }

    selectedRows.value = [];
    
    updateTotals();
};

// 分页查询产品库存信息
function productFill() {
 
    axios.get("http://localhost:5181/api/Inv_Stock/Get_Select_stock_All", {
        params: {
            weahouse_code: qty_order.warehouse_code,
            pro_code: productcode.value,
            dict_code: dict_code.value,
            currentPage: currentPage.value,
            pageSize: pageSize.value
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        productData.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}

// 查询产品库存总数
const productCount = () => {
    
    axios.get("http://localhost:5181/api/Inv_Stock/Get_Select__stock_Count", {
        params: {
            weahouse_code: qty_order.warehouse_code,
            pro_code: productcode.value,
            dict_code: dict_code.value,
        },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then((result) => {
        pageCount.value = result.data || 0
    }).catch((err) => {
        console.error(err);
    });
};




function handleSizeChange(val) {
    pageSize.value = val;
    productFill();
}

function handleCurrentChange(val) {
    currentPage.value = val;
    productFill();
}

// 查询计量单位
function getMeasure() {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
            dict_type: "db_measure"
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        measureOptios.value = result.data
        measureOptios.value = [{
            dict_value: "0", dict_label: "请选择单位"
        }, ...result.data]
    }).catch((err) => {
        console.info(err)
    });
}

// 根据计量单位id返回计量单位名称
function measureValue(row) {
    if (!row) return "无";
    const unit = measureOptios.value.find((item) => item.dict_value == row);
    return unit ? unit.dict_label : "无";
}

// 查询盘点类型
function getCheckTypes() {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
            dict_type: "Inv_Qty"
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        options.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}

// 查询仓库信息
function getWarehouses() {
    axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBy_Selectpd", {
        headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') }
    }).then((res) => {
        warehouses.value = res.data || [];
    }).catch((res) => {
        console.log(res);
    });
}

// 根据选择条件查询产品库存信息
function productSearch() {
    productFill()
    productCount()
    zone_codeSelect()
}

// 重置条件查询
function productReset() {
    productcode.value = ""
    dict_code.value = "0"
    productFill()
    productCount()
}

// 表格选择变化时的处理函数
const handleSelectionChange = (val) => {
    selectedProducts.value = val;
};  

// 点击确定存储选择的产品数据
const handleConfirmSelection = () => {
    const newProducts = selectedProducts.value.map(item => ({
        ...item,
        inventory_numder: 0,   
        pro_name: item.stock_name,
        pro_model: item.stock_model,
        proddti_profit: 0,
        proddti_loss: 0,
        proddti_profit_money: 0,
        proddti_loss_money: 0,
        location_code: "",
        location_name: "",
        isEditable: true, // ✅ 新增产品默认可编辑
        }));
   
    selectedData.value = [...selectedData.value, ...newProducts];
    dialogTableVisible.value = false;
    multipleTableRef.value.clearSelection();
    
    updateTotals();
}

// 表格选择变化时处理数据
const handleSelectedChange = (val) => {
    selectedRows.value = val;
};

// 判断以添加过的产品数据不能再次添加
const isDisabled = (row) => {
    return !selectedData.value.some(
        item => item.pro_code === row.pro_code && item.stock_entry_no === row.stock_entry_no
    );
};

// 退出页面
function handleClose() {
    router.push('/main/Inv/InvQty');
}

onMounted(() => {
    // 加载修改数据
    loadEditData();

    getMeasure();
    getCheckTypes();
});
</script>

<style scoped>
.inventory-check-form {
    padding: 20px;
    background-color: #fff;
    position: relative;
    min-height: calc(100vh - 100px);
    padding-bottom: 80px;
}

.section {
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    background: #fff;
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
    color: #2c3e50;
  
    padding-left: 10px;
}

.button-group {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
    padding-top: 20px;
    
}

.audit-section {
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    background: #f9f9f9;
}

.audit-info {
    padding: 15px;
    background: #fff;
    border-radius: 4px;
    border: 1px solid #ebeef5;
}

.audit-info div {
    margin-bottom: 10px;
    font-size: 14px;
}

.audit-label {
    font-weight: bold;
    color: #606266;
    display: inline-block;
    width: 80px;
}

.profit-color {
    color: #67C23A;
}

.loss-color {
    color: #F56C6C;
}
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    padding-top: 15px;
    border-top: 1px solid #ebeef5;
    
}
</style>